<?php
namespace statistics\utils;
/******************************************************************************
 * Controlls access and privileges of user.
*
* Copyright    : (c) 2004 - 2013 The Admidio Team
* Homepage     : http://www.admidio.org
*
* License      : GNU Public License 2 http://www.gnu.org/licenses/gpl-2.0.htm
****************************************************************************
*/
require_once (substr ( __DIR__, 0, strpos ( __DIR__, 'statistics' ) + 10 ) . DIRECTORY_SEPARATOR . 'includes.php');

class AccessControlManager{
	
	const CONFIG_PRIVILEGE = 'config';
	const SHOW_PRIVILEGE = 'show';
	const INSTALL_PRIVILEGE = 'install';
	
	private $privileges = array (
		'CONFIG_PRIVILEGE' => 'config',
		'SHOW_PRIVILEGE' => 'show',
		'INSTALL_PRIVILEGE' => 'install'	
	);
	
	private static $instance = null;
	
	public static function getInstance()
	{
		if (self::$instance === null)
		{
			self::$instance = new self;
		}
		return self::$instance;
	}
	
	private function __construct(){

	}
	
	private function  __clone(){}
	
	public function checkUserHasAnyPlgs(){
		$hasAnyPlgs = false;
		foreach ($this->privileges as $privilege){
			$hasAnyPlgs = $this->checkUserPrivilege($privilege);
			if ($hasAnyPlgs){
				break;
			}		
		}
		return $hasAnyPlgs;
	}
	
	public function checkUserPrivilege($privilege){
		$hasPrivilege = false;
		switch ($privilege){
			case self::SHOW_PRIVILEGE:
				$hasPrivilege = $this->checkIfUserHasShowPlgs();
				break;
			case self::CONFIG_PRIVILEGE:
				$hasPrivilege = $this->checkIfUserHasConfigPlgs();
				break;
			case self::INSTALL_PRIVILEGE:
				$hasPrivilege = $this->checkIfUserHasInstallPlgs();
				break;
		}
		return $hasPrivilege;
	}
	
	private function checkIfUserHasConfigPlgs() {
		global $plgAllowConfig;
		return $this->checkIfUserHasPlgs ( $plgAllowConfig );
	}
	
	private function checkIfUserHasShowPlgs() {
		global $plgAllowShow;
		return $this->checkIfUserHasPlgs ( $plgAllowShow );
	}
	
	private function checkIfUserHasInstallPlgs() {
		global $plgAllowInstall;
		return $this->checkIfUserHasPlgs ( $plgAllowInstall );
	}
	
	private function checkIfUserHasPlgs($plgAllow) {
	
		global $gValidLogin;
		global $gCurrentUser;
	
		$hasAccess = false;
	
		foreach ( $plgAllow as $i ) {
			if ($i == 'Benutzer' && $gValidLogin == true) {
				$hasAccess = true;
			} elseif ($i == 'Rollenverwalter' && $gCurrentUser->assignRoles ()) {
				$hasAccess = true;
			} elseif ($i == 'Listenberechtigte' && $gCurrentUser->viewAllLists ()) {
				$hasAccess = true;
			} elseif (hasRole ( $i )) {
				$hasAccess = true;
			}
		}
	
		return $hasAccess;
	}
	
}

?>